package com.tusuo.stds.ui.register;

import android.content.Context;
import android.graphics.Color;
import android.support.annotation.NonNull;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.andreabaccega.widget.FormEditText;
import com.flyco.animation.BaseAnimatorSet;
import com.flyco.animation.FadeEnter.FadeEnter;
import com.flyco.animation.FadeExit.FadeExit;
import com.flyco.dialog.listener.OnBtnClickL;
import com.flyco.dialog.widget.NormalDialog;
import com.tusuo.stds.Constants;
import com.tusuo.stds.R;
import com.tusuo.stds.ui.ToolbarOwner;
import com.tusuo.stds.ui.BaseToolbarActivity;
import com.tusuo.stds.ui.login.ThirdLoginUserInfo;
import com.tusuo.stds.util.Utils;
import com.tusuo.stds.util.validator.CaptchaValidator;
import com.tusuo.stds.util.validator.MobilePhoneNumberValidator;
import com.tusuo.stds.util.validator.PasswordValidator;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.ViewById;
import org.androidannotations.annotations.res.ColorRes;
import org.androidannotations.annotations.res.StringRes;

import java.util.HashMap;

import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.PlatformDb;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.sina.weibo.SinaWeibo;
import cn.sharesdk.tencent.qq.QQ;
import cn.sharesdk.wechat.friends.Wechat;
import myandroid.library.util.ApplicationHelper;

@EActivity(R.layout.activity_register)
public class RegisterActivity extends BaseToolbarActivity<RegisterView, RegisterPresenter>
                                implements RegisterView {

    @ViewById(R.id.register_layout_wechat)
    LinearLayout layoutWechat;
    @ViewById(R.id.tv_msg)
    TextView tvMsg;
    @ViewById(R.id.et_mobile_num)
    FormEditText etMobileNum;
    @ViewById(R.id.et_password)
    FormEditText etPassword;
    @ViewById(R.id.et_captcha)
    FormEditText etCaptcha;
    @ViewById(R.id.register_btn_get_captcha)
    Button btnGetCaptcha;
    @ViewById(R.id.register_btn_register)
    Button btnRegister;

    @StringRes(R.string.toolbar_title_register)
    String toolbarTitle;
    @StringRes(R.string.err_msg_mobile_number)
    String strErrMsgMobileNumber;
    @StringRes(R.string.err_msg_password)
    String strErrMsgPassword;
    @StringRes(R.string.err_msg_captcha)
    String strErrMsgCaptcha;
    @StringRes(R.string.login_3rd_login_tip)
    String strThirdLoginTip;

    @ColorRes(R.color.colorPrimary)
    int toolbarBgColor;
    @ColorRes(R.color.textColorPrimary)
    int toolbarTextColor;

    private NormalDialog mDialog;

    @AfterViews
    void afterViews() {
        setupUI(this, toolbarBgColor, toolbarTextColor);

        ToolbarOwner.Config config = new ToolbarOwner.Config(toolbarTitle, true, R.drawable.ic_back_dark, null);
        mToolbarOwner.setConfig(config);

        etMobileNum.addValidator(new MobilePhoneNumberValidator(strErrMsgMobileNumber));
        etPassword.addValidator(new PasswordValidator("格式不正确"));
        etCaptcha.addValidator(new CaptchaValidator(strErrMsgCaptcha));

        btnRegister.setEnabled(false);

        etMobileNum.addTextChangedListener(new EditTextChangedListener());
        etPassword.addTextChangedListener(new EditTextChangedListener());
        etCaptcha.addTextChangedListener(new EditTextChangedListener());

        initDialog();

        if (!Utils.App.isWXAppInstalled(this)) {
            layoutWechat.setVisibility(View.GONE);
        }

        ApplicationHelper.getInstance().addActivity(this);
    }

    @Override
    public void onBackPressed() {
        if (presenter.canGoBack()) {
            super.onBackPressed();
        } else {
            showTipDialog();
        }
    }

    @Override
    protected void onDestroy() {
        if (mDialog != null) {
            mDialog.superDismiss();
            mDialog = null;
        }
        super.onDestroy();
    }

    @NonNull
    @Override
    public RegisterPresenter createPresenter() {
        return new RegisterPresenter(this);
    }

    @Override
    public void setCaptchaBtnEnabled(boolean enabled) {
        btnGetCaptcha.setEnabled(enabled);
    }

    @Override
    public void setCaptchaBtnText(String text) {
        btnGetCaptcha.setText(text);
    }

    @Override
    public void showErrMsg(String text) {
        tvMsg.setText(text);
        tvMsg.setTextColor(Color.RED);
    }

    @Override
    public void showSlogan() {
        tvMsg.setText(getString(R.string.slogan));
        tvMsg.setTextColor(Color.WHITE);
    }

    @Override
    public void showTipDialog() {
        mDialog.show();
    }

    private void initDialog() {
        BaseAnimatorSet bas_in = new FadeEnter();
        BaseAnimatorSet bas_out = new FadeExit();

        mDialog = new NormalDialog(this);
        mDialog.isTitleShow(false)
                .bgColor(Color.parseColor("#FFFFFF"))
                .cornerRadius(5)
                .content(getString(R.string.dlg_title_captcha))
                .contentGravity(Gravity.CENTER)
                .contentTextColor(Color.parseColor("#333333"))
                .dividerColor(Color.parseColor("#CCCCCC"))
                .btnText("返回上一步", "确定")
                .btnTextSize(15.5f, 15.5f)
                .btnTextColor(Color.parseColor("#333333"), Color.parseColor("#0092FF"))
                .widthScale(0.7f)
                .showAnim(bas_in)
                .dismissAnim(bas_out);

        mDialog.setOnBtnClickL(
                new OnBtnClickL() {
                    @Override
                    public void onBtnClick() {
                        mDialog.dismiss();
                        RegisterActivity.this.finish();
                    }
                },
                new OnBtnClickL() {
                    @Override
                    public void onBtnClick() {
                        mDialog.dismiss();
                    }
                }
        );
    }

    @Click(R.id.register_btn_get_captcha)
    void clickGettingCaptchaBtn() {
        if (Utils.UI.isFastDoubleClick()) {
            return;
        }

        if (!etMobileNum.testValidity()) {
            presenter.showErrMsg(strErrMsgMobileNumber);
            return;
        }

        presenter.getCaptcha(etMobileNum.getText().toString());
    }

    @Click(R.id.register_btn_register)
    void clickRegisterBtn() {
        if (Utils.UI.isFastDoubleClick()) {
            return;
        }

        // 强制隐藏软键盘
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);

        if (!etMobileNum.testValidity()) {
            presenter.showErrMsg(strErrMsgMobileNumber);
            return;
        }

        if (!etPassword.testValidity()) {
            if (etPassword.getText().length() >= 6 && etPassword.getText().length() <= 30) {
                presenter.showErrMsg("密码不能含有特殊字符");
            }else {

                presenter.showErrMsg(strErrMsgPassword);
            }
            return;
        }

        if (!etCaptcha.testValidity()) {
            presenter.showErrMsg(strErrMsgCaptcha);
            return;
        }



        presenter.register(etMobileNum.getText().toString(),
                etPassword.getText().toString(),
                etCaptcha.getText().toString());
    }

    @Click({R.id.register_layout_qq, R.id.register_btn_qq, R.id.register_tv_qq})
    void loginAsQqAccount() {
        Utils.UI.showToastShort(strThirdLoginTip);
        Platform qq = ShareSDK.getPlatform(QQ.NAME);
        qq.removeAccount(true);
        authorize(qq);
    }

    @Click({R.id.register_layout_wechat, R.id.register_btn_wechat, R.id.register_tv_wechat})
    void loginAsWeChatAccount() {
        Utils.UI.showToastShort(strThirdLoginTip);
        Platform weChat = ShareSDK.getPlatform(Wechat.NAME);
        weChat.removeAccount(true);
        authorize(weChat);
    }

    @Click({R.id.register_layout_sina, R.id.register_btn_sina, R.id.register_tv_sina})
    void loginAsSinaWeiboAccount() {
        Utils.UI.showToastShort(strThirdLoginTip);
        Platform sinaWeibo = ShareSDK.getPlatform(SinaWeibo.NAME);
        sinaWeibo.removeAccount(true);
        authorize(sinaWeibo);
    }

    //执行授权,获取用户信息
    //文档：http://wiki.mob.com/Android_%E8%8E%B7%E5%8F%96%E7%94%A8%E6%88%B7%E8%B5%84%E6%96%99
    private void authorize(final Platform plat) {
        if (plat == null) {
            return;
        }

        plat.setPlatformActionListener(new PlatformActionListener() {
            @Override
            public void onComplete(Platform platform, int action, HashMap<String, Object> res) {

                if (action == Platform.ACTION_USER_INFOR) {
                    PlatformDb platDB = platform.getDb();//获取数平台数据DB

                    ThirdLoginUserInfo info = new ThirdLoginUserInfo();
                    info.openId = platDB.getUserId();
                    switch (plat.getName()) {
                        case "Wechat":
                            info.platForm = Constants.PLATFORM.WECHAT;
                            break;
                        case "QQ":
                            info.platForm = Constants.PLATFORM.QQ;
                            break;
                        case "SinaWeibo":
                            info.platForm = Constants.PLATFORM.WEIBO;
                            break;
                        default:
                            Utils.UI.showToastShort("第三方登录操作失败");
                            return;
                    }
                    info.accessToken = platDB.getToken();
                    info.nickName = platDB.getUserName();
                    // 别放Toast! ShareSDK会报错！
                    presenter.thirdLogin(info);
                } else {
                    Utils.UI.showToastShort("第三方登录操作失败");
                }
            }

            @Override
            public void onError(Platform platform, int action, Throwable throwable) {
                if (action == Platform.ACTION_USER_INFOR) {
                    PlatformDb platDB = platform.getDb();//获取数平台数据DB

                    ThirdLoginUserInfo info = new ThirdLoginUserInfo();
                    info.openId = platDB.getUserId();
                    switch (plat.getName()) {
                        case "Wechat":
                            info.platForm = Constants.PLATFORM.WECHAT;
                            break;
                        case "QQ":
                            info.platForm = Constants.PLATFORM.QQ;
                            break;
                        case "SinaWeibo":
                            info.platForm = Constants.PLATFORM.WEIBO;
                            break;
                        default:
                            Utils.UI.showToastShort("第三方登录操作失败");
                            return;
                    }
                    info.accessToken = platDB.getToken();
                    info.nickName = platDB.getUserName();
                    // 别放Toast! ShareSDK会报错！
                    presenter.thirdLogin(info);
                } else {
                    Utils.UI.showToastShort("第三方登录操作失败");
                }
            }

            @Override
            public void onCancel(Platform platform, int action) {
                Utils.UI.showToastShort("第三方登录操作取消");
            }
        });

        // 登录的时候走客户端,如果没有客户端会调转到网页版
        plat.SSOSetting(false);
        plat.showUser(null);//执行登录，登录后在回调里面获取用户资料
    }

    private class EditTextChangedListener implements TextWatcher {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            if (etMobileNum.getText().length() > 0
                    && etPassword.getText().length() > 0
                    && etCaptcha.getText().length() > 0) {
                btnRegister.setBackgroundResource(R.drawable.selector_theme_button);
                btnRegister.setEnabled(true);
            } else {
                btnRegister.setBackgroundResource(R.drawable.shape_theme_button_disabled);
                btnRegister.setEnabled(false);
            }


        }

        @Override
        public void afterTextChanged(Editable s) {
        }
    }
}
